﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="DisplayAttributes.cs" company="JDML Consulting Ltd.">
//   Copyright 2011 Photon Project - http://photon.codeplex.com
// </copyright>
// <summary>
//   Defines the DisplayAttributes type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Photon.ComponentModel
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.Reflection;
    using System.Text;
    using Reflection;

    public static class DisplayAttributes
    {
        public static string GetDisplayName(MemberInfo member)
        {
            var displayName = GetDisplayNameFromDisplayAttribute(member);
            if (!string.IsNullOrEmpty(displayName))
            {
                return displayName;
            }

            return MemberNameToDisplayName(member.Name);
        }

        private static string MemberNameToDisplayName(IEnumerable<char> memberName)
        {
            var output = new StringBuilder();
            foreach (var c in memberName)
            {
                if (output.Length > 0)
                {
                    if (Char.IsUpper(c) && Char.IsLower(output[output.Length - 1]))
                    {
                        output.Append(' ');
                    }
                }

                output.Append(c);
            }

            return output.ToString();
        }

        private static string GetDisplayNameFromDisplayAttribute(MemberInfo member)
        {
            var displayAttribute = member.GetCustomAttribute<DisplayAttribute>();
            return displayAttribute != null ? displayAttribute.Name : null;
        }
    }
}
